package com.boot2.core.service;

import com.boot2.core.dao.i.PositionCityDao;
import com.boot2.core.dao.i.PositionDistrictDao;
import com.boot2.core.dao.i.PositionProvinceDao;
import com.boot2.core.dao.i.UserLogDao;
import com.boot2.core.dao.mybatis.MyBatisBaseDao;
import com.boot2.core.model.AbstractLog;
import com.boot2.core.model.PositionCity;
import com.boot2.core.model.PositionDistrict;
import com.boot2.core.model.PositionProvince;
import com.boot2.core.utils.StringUtils;
import lombok.Data;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangweilin
 * @description: xxxxx
 * @date 2019/3/18
 */
@Data
@CommonsLog
@EnableAsync
public abstract class AbstractLogService<T extends AbstractLog> extends MyBatisBaseDao<AbstractLog> {

    @Autowired(required = false)
    UserLogDao<T> userLogDao;
    @Autowired(required = false)
    PositionProvinceDao positionProvinceDao;
    @Autowired(required = false)
    PositionCityDao positionCityDao;
    @Autowired(required = false)
    PositionDistrictDao positionDistrictDao;

    /**
     * @return
     */
    public HttpServletRequest request() {
        return AopService.httpRequestThreadLocal.get();
    }

    /**
     * 保存
     *
     * @param t
     */
//    @Async
    public void saveLog(T t) {

        //关联省id
        String provinceName = t.getProvinceName();
        if (StringUtils.isNotEmpty(provinceName)) {
            PositionProvince positionProvince = positionProvinceDao.findFirstByProvinceName(provinceName);
            if (null != positionProvince) {
                t.setProvinceId(positionProvince.getId());
            }
        }

        //关联市 id
        String cityName = t.getCityName();
        if (StringUtils.isNotEmpty(cityName)) {
            PositionCity positionCity = positionCityDao.findFirstByCityName(cityName);
            if (null != positionCity) {
                t.setCityId(positionCity.getId());
            }
        }

        //关联区县 id
        String districtName = t.getDistrictName();
        if (StringUtils.isNotEmpty(districtName)) {
            PositionDistrict district = positionDistrictDao.findFirstByCityNameAndDistrictName(cityName, districtName);
            if (null != district) {
                t.setDistrictId(district.getId());
            }
        }

        warpAbstractLog(t);
        userLogDao.saveAndFlush(t);

    }

//    protected abstract void saveAndFlush(T t);

    /**
     * 业务中扩展业务属性
     *
     * @param t
     */
    protected T warpAbstractLog(T t) {
        return t;
    }
}
